#define _DEFAULT_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#define CHILD_NUM 2

void child_things(void);
void parent_things(pid_t *);
void sighandler(int);

int main(void){
    pid_t pids[CHILD_NUM] = {0};
    for(int i = 0; i < CHILD_NUM; ++i)
    {
        pids[i] = fork();
        switch(pids[i])
        {
            case 0:
                child_things();
                break;
            case -1:
                perror("fork");
                return 1;
            default:
                break;

        }
    }

    parent_things(pids);

    int status[CHILD_NUM] = {0};
    for (int i = 0; i < CHILD_NUM; ++i)
        wait(status + i);

    return 0;
}

void parent_things(pid_t *children)
{
    int h = 0;
    char c = 0;
    while(1)
    {
        c = getchar();
        if (c == EOF || c == 'q')
            break;
        if(c == '\n')
            kill(children[h], SIGUSR1);
        h = (h + 1) % CHILD_NUM;
    }

    for (int i = 0; i < CHILD_NUM; ++i)
        kill(children[i], SIGINT);
}

void child_things(void)
{
    signal(SIGUSR1, sighandler);
    while(1);
    _exit(0);
}

void sighandler(int unused)
{
    (void) unused;
    puts("SIGUSR1 received");
}
